const app = getApp();
const api = require('../../utils/api');
import QRCode from '../../utils/weapp-qrcode'; //引入生成二维码的插件

Page({
    data: {
        status: '', //订单状态
        afterSalesStatus: '', //退货状态
        statusList: [
            {id: 0, status: '', afterSalesStatus: '', title: '全部'},
            {id: 1, status: 1, afterSalesStatus: 0, title: '待支付'},
            {id: 2, status: 2, afterSalesStatus: 0, title: '待核销'},
            {id: 3, status: 4, afterSalesStatus: 0, title: '已完成'},
            {id: 4, status: 3, afterSalesStatus: 0, title: '已取消'},
            {id: 5, status: '', afterSalesStatus: 4, title: '已退款'},
        ],
        statusIndex: 0,
        boxWidth: 0,
        boxLeft: 0,
        tagScroll: 0, //标签栏滚动距离

        orderList: [],
        pageNum: 1,
        pageSize: 10,
        total: 0,
        noContent: false, //无数据
        isFinished: false, //加载结束

        showWriteoffQrcode: false, //核销二维码弹窗
        writeoffQrcodeUrl: '', //核销二维码链接
    },
    onLoad(options) {
        //获取scrollview的宽度
        const query = wx.createSelectorQuery();
        query.select('#tagBox').boundingClientRect(res => {
            this.setData({
                boxWidth: res.width / 2,
            });
        }).exec();

        if(options.type) { //链接带参数
            this.data.statusList.forEach((item, index) => {
                if(item.status == parseInt(options.type) && item.afterSalesStatus == 0) {
                    this.switchTab(index);
                }
            });
        } else { //链接不带参数
            this.setData({
                tagScroll: 0
            });
            this.getData();
        }
    },
    onShow() {
        
    },
    
    getData() { //获取列表数据
        let params = {
            orderStatus: this.data.status, //订单状态：1.待付款 2.已付款 3.已取消
            afterSalesStatus: this.data.afterSalesStatus,
            pageNum: this.data.pageNum,
            pageSize: this.data.pageSize
        }
        api.post('/order/page', params)
            .then(res => {
                let list = res.content;
                //整理数据
                list.forEach(item => {
                    //日期格式化
                    item.createTime = app.filterDate(item.createTime);
                    //价格格式化
                    item.payableAmount = item.payableAmount.toFixed(2);
                    //计算消费券总数
                    let couponAmount = 0;
                    item.skuList.forEach(pro => {
                        couponAmount = couponAmount + (pro.memberCoupon * pro.quantity);
                        pro.price = pro.price.toFixed(2);
                        pro.memberPrice = pro.memberPrice.toFixed(2);
                    });
                    item.couponAmount = couponAmount;
                });
                let newList = [...this.data.orderList, ...list];

                this.setData({
                    orderList: newList,
                    total: res.total
                });

                //是否无内容标识
                if(this.data.orderList.length == 0) {
                    this.setData({
                        noContent: true
                    })
                } else {
                    this.setData({
                        noContent: false
                    });
                }
                //是否加载完毕标识
                if(this.data.orderList.length >= this.data.total) {
                    this.setData({
                        isFinished: true
                    })
                } else {
                    this.setData({
                        isFinished: false
                    })
                }
                wx.stopPullDownRefresh();
            })
    },
    switchTab(e) { //切换列表
        let index = e.currentTarget == undefined ? e : e.currentTarget.dataset.index;

        //计算标签距离左边的距离
        const query = wx.createSelectorQuery();
        query.select('#tag'+index).boundingClientRect(res => {
            let left = res.left;
            let self = res.width / 2;
            let width = left + self;
            if(width > this.data.boxWidth) {
                this.setData({
                    tagScroll: width - this.data.boxWidth,
                });
            } else {
                this.setData({
                    tagScroll: 0
                });
            }
        }).exec();
        
        this.setData({
            statusIndex: index,
            status: this.data.statusList[index].status,
            afterSalesStatus: this.data.statusList[index].afterSalesStatus,
            orderList: [],
            pageNum: 1,
            total: 0,
            isFinished: false,
        });
        this.getData();
    },

    //订单操作
    viewDetail(e) { //查看详情
        let id = e.currentTarget.dataset.id;
        wx.navigateTo({
            url: '/pages/orderDetail/orderDetail?id=' + id,
        });
    },
    gotoPay(e) { //去支付
        let id = e.currentTarget.dataset.id;
        wx.navigateTo({
            url: '/pages/orderPay/orderPay?id=' + id,
        });
    },
    cancelOrder(e) { //取消订单
        let item = e.currentTarget.dataset.item;
        let index = e.currentTarget.dataset.index;
        wx.showModal({
            title: '温馨提示',
            content: `您是否确认取消【${item.pickupName}】商家的订单【${item.orderNo}】？`,
            success: res => {
                if(res.confirm) {
                    api.post('/order/cancel?id=' + item.id)
                        .then(() => {
                            wx.showToast({
                                title: '订单已取消',
                                icon: 'none'
                            });

                            //刷新列表数据
                            if(this.data.status) {
                                this.setData({
                                    orderList: [],
                                    pageNum: 1,
                                    total: 0,
                                    isFinished: false,
                                });
                                this.getData();
                            } else {
                                this.setData({
                                    [`orderList[${index}].orderStatus`]: 3
                                })
                            }
                        })
                }
            }
        });
    },

    writeoffOrder(e) { //核销订单
        let id = e.currentTarget.dataset.id;
        this.setData({
            showWriteoffQrcode: true
        });

        this.createWriteoffQrcode(id);
    },
    closeWriteoff() {
        this.setData({
            showWriteoffQrcode: false
        });
    },
    createWriteoffQrcode(id) { //生成二维码
        let text = {
            k: 'ORDER_WRITEOFF',
            v: {
                id: id
            }
        }
        new QRCode('myQrcode', {
            text: JSON.stringify(text),
            width: this.createRpx2px(500),
            height: this.createRpx2px(500),
            padding: 12, // 生成二维码四周自动留边宽度，不传入默认为0
            correctLevel: QRCode.CorrectLevel.L, // 二维码可辨识度
            callback: res => {
                this.setData({
                    writeoffQrcodeUrl: res.path
                });
            }
        });
    },
    createRpx2px(rpx) {
        return wx.getSystemInfoSync().windowWidth / 750 * rpx
    },

    onPullDownRefresh() {
        //下拉刷新
        this.setData({
            orderList: [],
            pageNum: 1,
            total: 0,
            isFinished: false,
        });
        this.getData();
    },
    onReachBottom() {
        //加载更多
        if(!this.data.isFinished) {
            this.setData({
                pageNum: this.data.pageNum+1,
            });
            
            setTimeout(() => {
                this.getData();
            }, 800);
        }
    },
})